<?php
require_once("includes/include.php");
$Helper = new Helper();
$Log = new Log();
class uploadFiles{
	public $Log;
	public $Helper;
	public function __construct(){
		$this->Log = new Log();
		$this->Helper = new Helper();
	}
	public function uploadIt(){
		$tempFile = $_FILES['Filedata']['tmp_name'];
		$postFolderArr = explode("/",$_REQUEST['folder']);
		$length = count($postFolderArr)-1;
		$postFolder = $postFolderArr[$length];
		//$event  = substr(strrchr($_REQUEST['eventId'],"/"),1);
		$event  = $_REQUEST['eventId'];
		$parentFolder = $_REQUEST['parentFolder'];
		
		$this->Log->write("folder:".$postFolder);
		$this->Log->write("eventId:".$event);
		$dao = new eventdao();
		$rootDir = $dao->getRootEventDir($event);
		if (!$rootDir){
			$dao->updateRootEventDir($event);
			$rootDir = $event;
		}
		$baseFolder = $this->Helper->getEventBaseFolder();
		if (!is_dir($baseFolder)){
			mkdir($baseFolder);
		}
		$tempRootDir = $baseFolder.$rootDir."/";
		if(!is_dir($tempRootDir)){
			mkdir($tempRootDir);
		}
		if ($postFolder&&$event==""){
			$tempDir = $tempRootDir.$postFolder."/";
		}else{
			$tempDir = $tempRootDir;
		}
		if (!is_dir($tempDir)){
			mkdir($tempDir);
		}
		
		date_default_timezone_set("Asia/shanghai");
		$tempDate = date("Y_m_d_H_i_s").rand(10000,99999);
		$subx= strrchr($_FILES['Filedata']['name'],".");
		$targetFile = $tempDir.$tempDate.$subx;
//		$fileName = $_FILES['Filedata']['name'];
//		$sub = strrchr($fileName,".");
//		$fileNamebefore = str_replace($sub,"",$fileName);
//		$fileNameConvert = base64_encode($fileNamebefore);
//		$endFileName = $fileNameConvert.$sub;
		//$targetFile = $tempDir.$endFileName;
		$this->Log->write("tempDir:".$tempDir);
		$this->Log->write("tempRootDir:".$targetFile);
		$move = move_uploaded_file($tempFile,$targetFile);
		if ($move){
			$dao = new eventdao();
			$add = $dao->addFile($_FILES['Filedata']['name'],$targetFile,$postFolder);
			if($add){
				$this->Log->write("added");
			}else{
				$this->Log->write("added failed");
			}
		}else{
			$this->Log->write("failed move file");
		}
		echo $targetFile;//must not delete this line;
		
	}
}
$upload = new uploadFiles();
if(!empty($_FILES)){
	$upload->uploadIt();
}else{
	echo "no files";
}
?>